package com.lanlian.cayman.view;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.lanlian.cayman.HqMsg;
import com.lanlian.cayman.R;
import com.lanlian.cayman.fragment.MarketFragment;
import com.lanlian.cayman.utils.MResUtil;
import com.lanlian.cayman.utils.NumberManager;
import com.lanlian.commonlib.bean.ProfitLossInfo;
import com.lanlian.commonlib.data.GoodsBean;
import com.lanlian.commonlib.event.EventCode;
import com.lanlian.commonlib.event.EventMessage;
import com.lanlian.commonlib.util.EventBusUtils;
import com.lanlian.utillib.DisplayUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * <pre>
 *     author : huxiaobo
 *     e-mail : huxiaobo@xlanlian.com
 *     date   : 2018/8/23 17:01
 *     desc   : 止盈止损明细查看对话框
 *     version: 1.0
 * </pre>
 */
public class ProfitLossDetailsDialog extends Dialog {

    private Context mContext;
    private ProfitLossInfo mProfitLossInfo;

    private TextView mTvContractName;
    private TextView mTvDirection;
    private TextView mTvCurrentPrice;
    private TextView mTvProfitLoss;
    private TextView mTvProfitPrice;
    private TextView mTvProfitMoney;
    private LinearLayout mLayProfitBack;
    private LinearLayout mLayLossBack;
    private TextView mTvProfitBackPrice;
    private TextView mTvProfitBackMoney;
    private TextView mTvLossPrice;
    private TextView mTvLossMoney;
    private TextView mTvLossBackPrice;
    private TextView mTvLossBackMoney;
    private TextView mTvNum;
    private TextView mTvType;
    private TextView mTvClose;

    private RelativeLayout mLayProfitWeituoPrice;
    private TextView mTvProfitWeituoPrice;
    private RelativeLayout mLayProfitBackWeituoPrice;
    private TextView mTvProfitBackWeituoPrice;
    private RelativeLayout mLayLossWeituoPrice;
    private TextView mTvLossWeituoPrice;
    private RelativeLayout mLayLossBackWeituoPrice;
    private TextView mTvLossBackWeituoPrice;

    private ScrollView mScrollView;

    public ProfitLossDetailsDialog(@NonNull Context context, ProfitLossInfo profitLossInfo) {
        super(context, R.style.customDialog);
        this.mContext = context;
        this.mProfitLossInfo = profitLossInfo;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_profit_loss_details);
        initView();
        WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(metrics);
        EventBusUtils.register(this);
        if (mProfitLossInfo.getPriceZsRt() == null && mProfitLossInfo.getPriceZyRt() == null) {
            mLayLossBack.setVisibility(View.GONE);
            mLayProfitBack.setVisibility(View.GONE);
        } else {
            mLayLossBack.setVisibility(View.VISIBLE);
            mLayProfitBack.setVisibility(View.VISIBLE);
        }
        if (mProfitLossInfo.getOrderType() == 1) {
            mLayProfitWeituoPrice.setVisibility(View.GONE);
            mLayLossWeituoPrice.setVisibility(View.GONE);
            mLayProfitBackWeituoPrice.setVisibility(View.GONE);
            mLayLossBackWeituoPrice.setVisibility(View.GONE);
        } else {
            mLayProfitWeituoPrice.setVisibility(View.VISIBLE);
            mLayLossWeituoPrice.setVisibility(View.VISIBLE);
            if (mProfitLossInfo.getPriceZsRt() == null && mProfitLossInfo.getPriceZyRt() == null) {
                mLayProfitBackWeituoPrice.setVisibility(View.GONE);
                mLayLossBackWeituoPrice.setVisibility(View.GONE);
            } else {
                mLayProfitBackWeituoPrice.setVisibility(View.VISIBLE);
                mLayLossBackWeituoPrice.setVisibility(View.VISIBLE);
            }
        }
        if (mScrollView.getHeight() < (int) (DisplayUtil.getScreenHeight(mContext) * 0.8)) {
            getWindow().setLayout(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        } else {
            getWindow().setLayout(LinearLayout.LayoutParams.WRAP_CONTENT, (int) (DisplayUtil.getScreenHeight(mContext) * 0.8));
        }
        setData();
        mTvClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
    }

    private void initView() {
        mTvContractName = findViewById(R.id.tv_contract_name);
        mTvDirection = findViewById(R.id.tv_direction);
        mTvCurrentPrice = findViewById(R.id.tv_current_price);
        mTvProfitLoss = findViewById(R.id.tv_profit_loss);
        mTvProfitPrice = findViewById(R.id.tv_profit_price);
        mTvProfitMoney = findViewById(R.id.tv_profit_money);
        mLayProfitBack = findViewById(R.id.lay_profit_back);
        mLayLossBack = findViewById(R.id.lay_loss_back);
        mTvProfitBackPrice = findViewById(R.id.tv_profit_back_price);
        mTvProfitBackMoney = findViewById(R.id.tv_profit_back_money);
        mTvLossPrice = findViewById(R.id.tv_loss_price);
        mTvLossMoney = findViewById(R.id.tv_loss_money);
        mTvLossBackPrice = findViewById(R.id.tv_loss_back_price);
        mTvLossBackMoney = findViewById(R.id.tv_loss_back_money);
        mTvNum = findViewById(R.id.tv_num);
        mTvType = findViewById(R.id.tv_type);
        mTvClose = findViewById(R.id.tv_close);
        mLayProfitWeituoPrice = findViewById(R.id.lay_profit_weituo_price);
        mTvProfitWeituoPrice = findViewById(R.id.tv_profit_weituo_price);
        mLayProfitBackWeituoPrice = findViewById(R.id.lay_profit_back_weituo_price);
        mTvProfitBackWeituoPrice = findViewById(R.id.tv_profit_back_weituo_price);
        mLayLossWeituoPrice = findViewById(R.id.lay_loss_weituo_price);
        mTvLossWeituoPrice = findViewById(R.id.tv_loss_weituo_price);
        mLayLossBackWeituoPrice = findViewById(R.id.lay_loss_back_weituo_price);
        mTvLossBackWeituoPrice = findViewById(R.id.tv_loss_back_weituo_price);
        mScrollView = findViewById(R.id.scroll_view);
    }

    private void setData() {
        mTvContractName.setText(mProfitLossInfo.getContractCode());
        mTvDirection.setText(mProfitLossInfo.getSide() == 1 ? "买" : "卖");
        mTvDirection.setTextColor(mProfitLossInfo.getSide() == 1 ? mContext.getResources().getColor(R.color.color_T7) :
                mContext.getResources().getColor(R.color.color_T8));
        mTvProfitPrice.setText(mProfitLossInfo.getPriceZy() == null ? "--" : mProfitLossInfo.getPriceZy().toPlainString());
        mTvProfitMoney.setText(mProfitLossInfo.getStopProfit() == null ? "--" : mProfitLossInfo.getStopProfit().toPlainString());
        mTvProfitBackPrice.setText(mProfitLossInfo.getPriceZyRt() == null ? "--" : mProfitLossInfo.getPriceZyRt().toPlainString());
        mTvProfitBackMoney.setText(mProfitLossInfo.getStopProfitRt() == null ? "--" : mProfitLossInfo.getStopProfitRt().toPlainString());
        mTvLossPrice.setText(mProfitLossInfo.getPriceZs() == null ? "--" : mProfitLossInfo.getPriceZs().toPlainString());
        mTvLossMoney.setText(mProfitLossInfo.getStopLoss() == null ? "--" : mProfitLossInfo.getStopLoss().toPlainString());
        mTvLossBackPrice.setText(mProfitLossInfo.getPriceZsRt() == null ? "--" : mProfitLossInfo.getPriceZsRt().toPlainString());
        mTvLossBackMoney.setText(mProfitLossInfo.getStopLossRt() == null ? "--" : mProfitLossInfo.getStopLossRt().toPlainString());
        mTvProfitWeituoPrice.setText(mProfitLossInfo.getLimitPriceZy() == null ? "--" : mProfitLossInfo.getLimitPriceZy().toPlainString());
        mTvLossWeituoPrice.setText(mProfitLossInfo.getLimitPriceZs() == null ? "--" : mProfitLossInfo.getLimitPriceZs().toPlainString());
        mTvProfitBackWeituoPrice.setText(mProfitLossInfo.getLimitPriceZyrt() == null ? "--" : mProfitLossInfo.getLimitPriceZyrt().toPlainString());
        mTvLossBackWeituoPrice.setText(mProfitLossInfo.getLimitPriceZsrt() == null ? "--" : mProfitLossInfo.getLimitPriceZsrt().toPlainString());
        mTvNum.setText(String.valueOf(mProfitLossInfo.getNum()));
        mTvType.setText(mProfitLossInfo.getOrderType() == 1 ? "市价" : "限价");
        if (mProfitLossInfo.getStatus() != 1) {
            mTvProfitLoss.setTextColor(mContext.getResources().getColor(R.color.color_text_style1));
            mTvCurrentPrice.setTextColor(mContext.getResources().getColor(R.color.color_text_style1));
            mTvProfitLoss.setText("--");
            mTvCurrentPrice.setText("--");
        }
        calculationPnl();
    }

    /**
     * 计算盈亏
     */
    private void calculationPnl(HqMsg.YsHqInfo ysHqInfo) {
        if (mProfitLossInfo.getFutureCode() == null ||
                mProfitLossInfo.getStatus() != 1) {
            return;
        }
        if (mProfitLossInfo.getFutureCode().equals(ysHqInfo.getCommodityNo() + ysHqInfo.getContractNo1())) {
            GoodsBean goodsBean = MarketFragment.getRespMarket().getGoods(mProfitLossInfo.getFutureCode());
            if (goodsBean == null) {
                return;
            }
            int count = NumberManager.getNumberDecimalDigits(goodsBean.minChange);
            mTvCurrentPrice.setText(NumberManager.getStringNoZero("1", String.valueOf(ysHqInfo.getQLastPrice()), count));
            double minChange = Double.parseDouble(goodsBean.minChange);
            int flag = mProfitLossInfo.getSide() == 1 ? 1 : -1;
            double priceUnit = Double.parseDouble(goodsBean.priceUnit);
            double pnl = (ysHqInfo.getQLastPrice() - mProfitLossInfo.getJj()) / minChange * priceUnit * flag
                    * mProfitLossInfo.getNum();
            mTvProfitLoss.setText(new BigDecimal(pnl).setScale(2, RoundingMode.HALF_DOWN).toPlainString());
            if (new BigDecimal(pnl).setScale(2, RoundingMode.HALF_DOWN).doubleValue() > 0) {
                mTvProfitLoss.setTextColor(MResUtil.getUpColor());
            } else if (new BigDecimal(pnl).setScale(2, RoundingMode.HALF_DOWN).doubleValue() < 0) {
                mTvProfitLoss.setTextColor(MResUtil.getDownColor());
            } else {
                mTvProfitLoss.setTextColor(MResUtil.getPingColor());
            }
        }
    }

    /**
     * 计算盈亏
     */
    private void calculationPnl() {
        if (mProfitLossInfo.getFutureCode() == null ||
                mProfitLossInfo.getStatus() != 1) {
            return;
        }
        GoodsBean goodsBean = MarketFragment.getRespMarket().getGoods(mProfitLossInfo.getFutureCode());
        if (goodsBean == null) {
            return;
        }
        int count = NumberManager.getNumberDecimalDigits(goodsBean.minChange);
        mTvCurrentPrice.setText(NumberManager.getStringNoZero("1", String.valueOf(mProfitLossInfo.getLastPrice()), count));
        double minChange = Double.parseDouble(goodsBean.minChange);
        int flag = mProfitLossInfo.getSide() == 1 ? 1 : -1;
        double priceUnit = Double.parseDouble(goodsBean.priceUnit);
        double pnl = (mProfitLossInfo.getLastPrice() - mProfitLossInfo.getJj()) / minChange * priceUnit * flag
                * mProfitLossInfo.getNum();
        mTvProfitLoss.setText(new BigDecimal(pnl).setScale(2, RoundingMode.HALF_DOWN).toPlainString());
        if (new BigDecimal(pnl).setScale(2, RoundingMode.HALF_DOWN).doubleValue() > 0) {
            mTvProfitLoss.setTextColor(MResUtil.getUpColor());
        } else if (new BigDecimal(pnl).setScale(2, RoundingMode.HALF_DOWN).doubleValue() < 0) {
            mTvProfitLoss.setTextColor(MResUtil.getDownColor());
        } else {
            mTvProfitLoss.setTextColor(MResUtil.getPingColor());
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBusUtils.unregister(this);
    }

    /**
     * 接收到分发的事件
     *
     * @param event 事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveEvent(EventMessage event) {
        switch (event.getCode()) {
            case EventCode.EVENT_MARKET:
                HqMsg.YsHqInfo ysHqInfo = (HqMsg.YsHqInfo) event.getData();
                calculationPnl(ysHqInfo);
                break;
            default:
                break;
        }
    }

}
